<template>
  <el-dialog
    class="form-add-edit dialog-dark-skin no-select"
    :title="actionName"
    :visible.sync="dialogAddEditVisible"
    width="34%"
    :close-on-click-modal="false"
  >
    <el-form ref="formData" :model="formData" label-width="100px" class="demo-userForm" :rules="rules">
      <el-scrollbar tag="div" class="is-empty" style="padding-right: 1px;" wrap-class="el-select-dropdown__wrap" view-class="el-select-dropdown__list">

        <el-form-item class="avatar-left-input" label="所属部门" prop="role_id">
          <!--          <el-select-->
          <!--            multiple-->
          <!--            collapse-tags-->
          <!--            style="display: block;"-->
          <!--            v-model="formData.dept_id"-->
          <!--            placeholder="请选择部门"-->
          <!--          >-->
          <!--            <el-option v-for="item in deptsData" :key="item.id" :label="item.name" :value="item.id"></el-option>-->
          <!--          </el-select>-->

          <el-cascader
            v-model="formData.dept_id"
            :options="deptsData"
            :props="{ expandTrigger: 'hover', checkStrictly: true, label: 'title', value: 'id' }"
            placeholder="请选择部门"
            style="display: block;"
            clearable
          />
        </el-form-item>

        <el-form-item label="岗位名称" prop="mobile">
          <el-input v-model="formData.title" size="small" />
        </el-form-item>

        <el-form-item label="岗位排序" prop="email">
          <el-input v-model="formData.sort" size="small" />
        </el-form-item>

        <el-form-item label="岗位状态">
          <el-radio v-model="formData.status" size="small" class="radio" border :label="1">开启</el-radio>
          <el-radio v-model="formData.status" size="small" class="radio" border :label="0">禁用</el-radio>
        </el-form-item>

        <el-form-item label="岗位描述" prop="email">
          <el-input v-model="formData.remark" size="small" type="textarea" />
        </el-form-item>

      </el-scrollbar>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="dialogAddEditVisible = false">取 消</el-button>
      <el-button size="small" type="primary" :loading="btnLoading" @click="submitUser">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
import validate from '@/utils/validate'
import search from '@/utils/search'
import { getToken } from '@/utils/auth'
import { saveLStorage, getLStorage, MD5 } from '@/utils/index'
import { add as userAdd, edit as userEdit } from '@/api/sys/post'
import { tree as deptTreeApi } from '@/api/sys/dept'

export default {
  name: 'PostAdd'
  , computed: {
    ...mapGetters([
      'fullHeight'
    ])

    , actionName() {
      return (this.isAddEdit ? '修改' : '新增') + '岗位'
    }
  }
  , data() {
    const validateUserName = (rule, value, callback) => {
      validate.validAlphabets()
      if (!value) {
        callback(new Error('请输入用户名'))
      } else if (value.length > 20 || value.length < 4) {
        callback(new Error('用户名只能在 4 ~ 20 字符之间'))
      } else if (!validate.validAlphaDash(value)) {
        callback(new Error('用户名只能为字母和数字、下划线_及破折号-'))
      } else {
        callback()
      }
    }

    const validateNickName = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入用户昵称'))
      } else if (value.length > 32 || value.length < 2) {
        callback(new Error('用户昵称只能在 2 ~ 32 字符之间'))
      } else if (!validate.validChsDash(value)) {
        callback(new Error('用户昵称只能为汉字、字母、数字和下划线_及破折号-'))
      } else {
        callback()
      }
    }

    const validateRoleId = (rule, value, callback) => {
      if (!value || !value.length) {
        callback(new Error('请选择角色'))
      } else {
        callback()
      }
    }

    const validatePassword = (rule, value, callback) => {
      if (this.isAddEdit && value === '') {
        callback()
      } else if (value === '') {
        callback(new Error('请输入密码'))
      } else if (value.length > 20 || value.length < 6) {
        callback(new Error('密码只能在 6 ~ 20 字符之间'))
      } else {
        callback()
      }
    }

    const validateRepassword = (rule, value, callback) => {
      if (!this.isAddEdit && !value) {
        callback(new Error('请输入确认密码'))
      } else if (value !== this.userForm.password) {
        callback(new Error('确认密码与密码不相同'))
      } else {
        callback()
      }
    }

    const validateMobile = (rule, value, callback) => {
      if (!!value && !validate.validMobile(value)) {
        callback(new Error('请输入正确手机号'))
      } else {
        callback()
      }
    }

    const validateEmail = (rule, value, callback) => {
      if (!!value && !validate.validEmail(value)) {
        callback(new Error('请输入邮箱号'))
      } else {
        callback()
      }
    }

    return {
      // 新增或修改
      roleData: []
      , deptData: []
      , selectDept: []
      , selectRole: []
      , dialogTitle: ''
      , dialogLoading: false
      , defaultProps: {
        children: 'children'
        , label: 'name'
        , id: 'id'
      }
      , defaultDepts: {
        children: 'children'
        , label: 'name'
        , id: 'id'
      }
      , formData: this.defaultForm()
      , rules: {
        title: [{ trigger: 'blur', validator: validateUserName }]
        // , dept_id: [{ trigger: 'blur', validator: validateRoleId }]
      }
      // role
      , deptsData: []
      // token
      , headersToken: {
        'token': getToken()
      }
      , btnLoading: false
      , isAddEdit: false
      , imageAction: this.uploadImg()
      , dialogAddEditVisible: false
      , complexFilterHeight: 0
    }
  }
  , created() {
    // 加载部门数据
    deptTreeApi().then(res => {
      if (res && res.data && res.data.rows) {
        this.deptsData = res.data.rows
      }
    })
  }
  , methods: {
    // 保存用户
    submitUser() {
      this.btnLoading = true
      // 重新验证数据
      this.$refs.formData.validate((res, res1) => {
        if (res) {
          if (this.isAddEdit) {
            // 判断id
            if (!this.formData.hasOwnProperty('id') || this.formData.id < 1) {
              return this.$message.error('参数错误请刷新后重试')
            }

            userEdit(this.formData).then(res => {
              // 重新加载数据
              this.load()
              // 按钮过渡
              this.btnLoading = false
              // 提示
              this.$message({
                type: 'success'
                , message: res.msg
              })

              // 管理弹框
              this.dialogAddEditVisible = false
            }).catch(res => {
              this.btnLoading = false
            })
          } else {
            userAdd(this.formData).then(res => {
              // 重新加载数据
              this.load()
              // 按钮过渡
              this.btnLoading = false
              // 提示
              this.$message({
                type: 'success'
                , message: res.msg
              })

              // 管理弹框
              this.dialogAddEditVisible = false
            }).catch(res => {
              this.btnLoading = false
            })
          }
        } else {
          this.btnLoading = false
        }
      })
    }

    // 修改
    , showAddEdit(row, type) {
      this.isAddEdit = type === true
      // 重置验证样式
      if (this.$refs['formData'] !== undefined) {
        this.$refs['form'].resetFields()
      }

      // 判断对应操作
      if (this.isAddEdit) {
        // 修改
        // 重置值
        for (var i in this.form) {
          if (row.hasOwnProperty(i) && i !== 'password') {
            this.form[i] = row[i]
            // 处理dept_id
            if (i === 'dept_id' && this.form[i].length > 0) {
              for (var j in this.form[i]) {
                this.form[i][j] = parseInt(this.form[i][j])
              }
            }
          } else {
            this.form[i] = this.defaultForm()[i]
          }
        }
        // 处理id
        this.form['id'] = row.id
      } else {
        // 判断是否有修改回填数据，有的话清除
        if (this.formData.hasOwnProperty('id')) {
          this.formData = this.defaultForm()
        }
      }

      // 显示弹窗
      this.dialogAddEditVisible = true
    }

    , defaultForm() {
      return {
        title: ''
        , sort: 0
        , status: 1
        , remark: ''
        , dept_id: []
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  @import "@/styles/element-variables.scss";
  $bg: #fff;
  $space: 0.625rem;
  $avatarWidth: 150px;

  .form-add-edit{
    .el-form-item{
      margin-bottom: 15px;
      &.avatar-left-input{
        margin-right: $avatarWidth;
      }
    }
  }
</style>

<style rel="stylesheet/scss" lang="scss">
  @import "src/styles/variables.scss";
  $avatarWidth: 150px;
  $avatarLeft: 12px;
  $imgBoxWidth: $avatarWidth - $avatarLeft;

  .form-add-edit{
    // 处理新增修改弹窗样式
    .el-dialog__header{
      background-color: $menuBg;
      .el-icon,
      .el-dialog__title{
        color: lighten($menuBg, 72%);
        font-weight: bold;
      }
    }

    .el-dialog__footer{
      border-top: 1px solid lighten($menuBg, 66%);
      background-color: lighten($menuBg, 70%);
      padding-bottom: 10px;
    }

    .el-select-dropdown__wrap{
      max-height: 60vh;
      .el-select-dropdown__list{
        position: relative;
      }
    }

    // 头像
    .avatar-uploader{
      display: inline-block;
      position: absolute;
      right: 0;
      .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 4px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        width: $imgBoxWidth;
        height: $imgBoxWidth;
        &:hover {
          border-color: #409EFF;
        }
        .avatar {
          width: 100%;
          height: 100%;
        }
        .avatar-uploader-icon {
          font-size: 28px;
          color: #8c939d;
          width: $imgBoxWidth;
          height: $imgBoxWidth;
          line-height: $imgBoxWidth;
          text-align: center;
        }
      }
    }
  }
</style>
